﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Net.Mail;

public partial class PasswordRecovery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblMessage.Visible = false;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {   
        //Create Connection String And SQL Statement
        string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(strConnection);

        //Get the password length from global settings and create a random password.
        string strpasswordlength = "Select PasswordLength from GlobalSetting";
        SqlCommand commandfinddbpwd = new SqlCommand(strpasswordlength, connection);
        connection.Open();
        string findpasswordlength = commandfinddbpwd.ExecuteScalar().ToString();
        
        int passwordlength = Convert.ToInt16(findpasswordlength);
        RandomPasswordGenerator example = new RandomPasswordGenerator();
        string randompassword = example.CreateRandomPassword(passwordlength);
      

         //Get the username and password from database.
        string strSelect = "SELECT UserName,Hash FROM [User] WHERE EmailAddress = @Email";
        SqlCommand command = new SqlCommand(strSelect,connection);
        

        SqlParameter email = new SqlParameter("@Email", SqlDbType.VarChar, 50);
        email.Value = txtEmail.Text.Trim().ToString();
       command.Parameters.Add(email);
 
       //Create Dataset to store results and DataAdapter to fill Dataset
        DataSet dsPwd = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter(command);
        
       dAdapter.Fill(dsPwd);
        connection.Close();

      try
        {
          // If email address record is found in database
            if (dsPwd.Tables[0].Rows.Count > 0)
            {

             //Create email information and email to user. 

                MailMessage loginInfo = new MailMessage();
                loginInfo.To.Add(txtEmail.Text.ToString());
                loginInfo.From = new MailAddress("stockmarketsimulation@hotmail.com");
                loginInfo.Subject = "Forgot User ID/Password Information";

                loginInfo.Body = "Username: " + dsPwd.Tables[0].Rows[0]["UserName"] + "<br><br>Password: " + randompassword + "<br><br>";
                loginInfo.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.live.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.Credentials = new System.Net.NetworkCredential("stockmarketsimulation@hotmail.com", "poiu1234");
                smtp.Send(loginInfo);
                lblMessage.Visible = true;
                lblMessage.Text = "Account Information is sent to your Email Address";
                lblMessage.ForeColor = System.Drawing.Color.Green;
                Response.Write("<script language='javascript'>alert('Account Information is sent to your Email Address.');window.location.href='PasswordRecovery.aspx'</script>");             

             //Insert new record to password history table the new random password and username.
                String stringcmd2 = "INSERT INTO [PasswordHistory] (userName,changeDate,hash,hash2) VALUES ('" + dsPwd.Tables[0].Rows[0]["Username"].ToString() + "', @changedate, @hash,@hash2 )";
                SqlCommand command3 = new SqlCommand(stringcmd2, connection);


                SqlParameter changedate = new SqlParameter("@changedate", SqlDbType.DateTime);
                changedate.Value = System.DateTime.Now;
                command3.Parameters.Add(changedate);

                SqlParameter hash2 = new SqlParameter("@hash2", SqlDbType.VarChar);
                hash2.Value = randompassword;
                command3.Parameters.Add(hash2);

             //Encrypt the randompassword and unlock the useraccount and updated the encrypted password in user table.
                string encryptedpwd = SSTCryptographer.Encrypt(randompassword, "SampleKey"); 
                string unlockacct = "Update [User] set IsAccountLocked='" + false + "', hash='" + encryptedpwd + "', hash2='" + randompassword +"' where UserName='" + dsPwd.Tables[0].Rows[0]["Username"].ToString() + "'";
                SqlCommand command2 = new SqlCommand(unlockacct, connection);

                SqlParameter hash = new SqlParameter("@hash", SqlDbType.VarChar);
                hash.Value = encryptedpwd;
                command3.Parameters.Add(hash);



                connection.Open();
                command2.ExecuteNonQuery();
                command3.ExecuteNonQuery();
                connection.Close();

            }

            else
            {

                //Display error msg when email address not found.
                lblMessage.Visible = true;
                lblMessage.Text = "Email Address Not Registered or Found";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }


        }

        catch (Exception ex)

        {
            
            lblMessage.Visible = true;
            lblMessage.Text = "Email failed to send " + ex.ToString();
            lblMessage.ForeColor = System.Drawing.Color.Red;
           
        
        }



    }
}